import {
  LOGIN_START,
  LOGIN_SUCCESS,
  LOGIN_FAIL
} from './actionTypes'
import {userLogin} from '../api/user'

export const loginStart = ()=>{ //开始登录
  return {
    type:LOGIN_START
  }
}

export const loginSuccess = ({payload,remember})=>{ //登录成功
  return {
    type:LOGIN_SUCCESS,
    payload,
    remember
  }
}

export const loginFail = ()=>{ //登录失败
  return {
    type:LOGIN_FAIL
  }
}

export const loginAsync = (userinfo,history)=>{  //异步登录的action
  return (dispatch)=>{
    dispatch(loginStart()) //开始登录
    console.log('开始登录');
    // 发起异步请求
    userLogin(userinfo).then(res=>{
      console.log('登录成功',res);
      dispatch(loginSuccess({//登录成功
        payload:res.data, 
        remember:userinfo.remember
      })) 
      //触发路由跳转
      history.push('/')
    }).catch(err=>{
      console.log('账号或密码错误');
      dispatch(loginFail()) //登录失败
    })
  }
}